<template>
  <div class="create">
    <el-card class="box-card">
      <h4>商品（spu）介绍</h4>
      <el-form label-width="150px" :model="form" ref="shopRef">
        <el-form-item label='商品名称' prop='title' :rules='[{required:true,message:"请输入商品名称"}]'>
          <el-input v-model.trim="form.title"/>
        </el-form-item>
        <el-form-item label='原始价格' prop='price' :rules='[{required:true,message:"请输入原始价格"}]'>
          <el-input v-model.trim="form.price">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label='当前价格' prop='originalPrice' :rules='[{required:true,message:"请输入当前价格"}]'>
          <el-input v-model.trim="form.originalPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label='VIP价格' prop='vipPrice' :rules='[{required:true,message:"请输入VIP价格"}]'>
          <el-input v-model.trim="form.vipPrice">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label='剩余库存'>
          <el-input :disabled='true' :value='0' />
        </el-form-item>
        <el-form-item label='运费模板'>
          <el-select v-model="form.freightTemplateId" placeholder="请选择运费模板">
            <el-option label="广东发包邮" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label='是否在售' prop='status' :rules='[{required:true,message:"请选择"}]'>
          <el-radio-group v-model="form.status" class="ml-4">
            <el-radio :label="1">在售</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label='商品图片'>
          <el-upload :limit='5' list-type="picture-card" :before-upload="beforeAvatarUpload" :file-list='picList' :headers='myHeaders' :on-success="handleAvatarSuccess" :action="imgPath" :on-remove="handleRemove">
            <el-icon v-if="!(form.imgList.length==5)">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label='商品单位' prop='unit' :rules='[{required:true,message:"请输入商品单位"}]'>
          <el-input placeholder="件/个/盒" v-model="form.unit" />
        </el-form-item>
        <el-form-item label='所属类目'>
          <el-cascader :options="category" v-model="form.categoryId" :props="part" clearable />
        </el-form-item>
        <el-form-item label='商品简介'>
          <el-input v-model="form.description" />
        </el-form-item>
        <el-form-item label='商品详情介绍' prop='detail' :rules='[{required:true,message:"请输入类型名称"}]'>
          <!-- <Editor :init='init' style="width:100%"></Editor> -->
          <!-- 富文本 -->
          <RichText v-model="form.detail"></RichText>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <strong>商品参数</strong>
      <div>
        <el-button type='primary' style="margin-top:10px" @click="paramAdd(1)">添加</el-button>
      </div>
      <!-- 参数表格 -->
      <el-table :data="form.attributeList" style="width:100%">
        <el-table-column label="商品参数名称" prop="attribute"></el-table-column>
        <el-table-column label="商品参数值" prop="value"></el-table-column>
        <el-table-column label="操作">
          <template #default='scope'>
            <el-button type='danger' @click="remove(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 参数弹出框 -->
      <el-dialog title="设置商品参数" v-model="dialogFormVisible" :destroy-on-close='true'>
        <el-form :model="formPran" ref="formRef" label-position='left' label-width="auto">
          <el-form-item label='商品参数名称' prop='attribute' :rules='[{required:true,message:"请输入名称"}]'>
            <el-input v-model="formPran.attribute" />
          </el-form-item>
          <el-form-item label='商品参数值' prop='value' :rules='[{required:true,message:"请输入商品参数值"}]'>
            <el-input v-model="formPran.value" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="confirm()">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
    <!-- 规格纬度 -->
    <el-card>
      <strong>规格纬度</strong>
      <div>
        <el-button type='primary' style="margin-top:10px" @click="paramAdd(0)">添加</el-button>
      </div>
      <!-- 规格表格 -->
      <el-table :data="form.specificationList" style="width:100%">
        <el-table-column label="纬度ID"></el-table-column>
        <el-table-column label="纬度名称" prop="title"></el-table-column>
        <el-table-column label="创建时间" prop="gmtCreate">
          <template #default='scope'>
            {{new Date(scope.row.gmtCreate).friendTime()}}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default='scope'>
            <el-button type='danger' @click="alter(scope.row,scope.$index)">修改</el-button>
            <el-button type='danger' @click="remove(scope.$index,0)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 规格弹出框 -->
      <el-dialog :title="bool?'创建规格':'修改规格'" v-model="specificationVisible" :destroy-on-close='true'>
        <el-form :model="specification" label-width="auto" @submit.prevent.native ref="formRef">
          <el-form-item label='类型名称' prop='title' label-width="150px" :rules='[{required:true,message:"请输入类型名称"}]'>
            <el-input v-model="specification.title" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="specificationVisible = false">取消</el-button>
            <el-button type="primary" @click="addspecification()">{{bool?'创建规格':'修改规格'}}</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
    <!-- 商品详情 -->
    <el-card>
      <strong>商品(Sku)详情</strong>
      <div>
        <el-button type='primary' style="margin-top:10px" @click="batch()">批量定价</el-button>
      </div>
      <!-- 批量价格弹出框 -->
      <el-dialog title="批量定价" v-model="priceVisible">
        <el-form v-model='skuPrice' label-width="100px" label-position='left' ref="popRef">
          <el-form-item label='现价(￥)'>
            <el-input-number :min="1" v-model="skuPrice.price" />
          </el-form-item>
          <el-form-item label='VIP价格(￥)'>
            <el-input-number :min="1" v-model="skuPrice.vipPrice" />
          </el-form-item>
          <el-form-item label='吊牌价(￥)'>
            <el-input-number :min="1" v-model="skuPrice.originalPrice" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="priceVisible = false">取消</el-button>
            <el-button type="primary" @click="batchConfirm">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 标签 -->
      <div v-for="(item,index) in form.specificationList" :key="index" style="margin:20px 0px">
        <el-space>
          <el-tag type="warning">{{item.title}}</el-tag>
          <el-tag v-for="(items,ind) in item.values" :key="ind" closable @close="form.specificationList[index].values.splice(ind, 1)">{{items}}</el-tag>
          <el-input v-if="item.inputSkuTagVisible" style="width:100px" v-model.trim="specification.inputSkuTagValue" size="small" @blur="handleInputConfirm(index)" />
          <el-button v-else class="button-new-tag ml-1" size="small" @click="addTab(index)">+ 添加 </el-button>
        </el-space>
      </div>
      <!-- sku列表 -->
      <el-table :data="createSku" style="width:100%" border :span-method="objectSpanMethod">
        <el-table-column :label="item.title" :prop="'id_'+item.title" v-for="(item,index) in form.specificationList" :key="index">
        </el-table-column>
        <el-table-column label="SkuId"></el-table-column>
        <el-table-column label="￥价格(元)" prop="price" width="180px">
          <template #default='scope'>
            <el-input-number v-model="scope.row.price" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="￥VIP价(元)" prop="vipPrice" width="180px">
          <template #default='scope'>
            <el-input-number v-model="scope.row.vipPrice" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="￥吊牌价(元)" prop="originalPrice" width="180px">
          <template #default='scope'>
            <el-input-number v-model="scope.row.originalPrice" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="库存(元)" prop="stock" width="180px">
          <template #default='scope'>
            <el-input-number v-model="scope.row.stock" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="重量(克)" prop="weight" width="180px">
          <template #default='scope'>
            <el-input-number v-model="scope.row.weight" />
          </template>
        </el-table-column>
        <el-table-column label="sku图片" prop="value">
          <template #default='scope'>
            <el-upload :headers='myHeaders' v-loading="loading" :show-file-list='false' :on-success="(res)=>{handleImgSuccess(res,scope.$index)}" :action="imgPath">
              <img v-if="scope.row.img" :src="scope.row.img" style="width:50px" />
              <div v-else class="box">
                <el-icon>
                  <Upload />
                </el-icon>
              </div>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="条形码" prop="barCode" width="300px">
          <template #default='scope'>
            <el-input v-model.trim="scope.row.barCode" style="width:300px">
              <template #append>
                <el-button @click="form.skuList[scope.$index].barCode = Date.now()">随机</el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="text-align:right;margin:20px">
      <el-button type="primary" @click="closeShop">关闭</el-button>
      <el-button type="primary" @click="addShop">保存商品</el-button>
    </div>
  </div>
</template>

<script>
import { post, imgUrl } from "@/utils/http";
// import Editor from "@tinymce/tinymce-vue";
import RichText from "@/components/tinymce/RichText.vue";
import Cookies from 'js-cookie'
import { Plus, Download, Upload } from '@element-plus/icons-vue';
var token = Cookies.get('token') // 获取token
export default {
  components: {
    Plus, Download, RichText, Upload
  },
  data() {
    return {
      form: {
        title: '',  //标题
        price: 0,  //价格
        originalPrice: 0,  //原价
        vipPrice: 0,  //会员价
        freightTemplateId: '',  //运费
        unit: '',  //单位
        categoryId: '', //类目
        img: '',
        status: 1,  //状态
        description: '', //简介
        detail: '',  //富文本
        imgList: [], //图片
        attributeList: [], //商品参数
        specificationList: [], //规格参数
        skuList: []  //sku列表
      },
      formPran: { //商品参数弹出框
        attribute: '', //输入框商品名称
        value: '',  //商品参数
      },
      specification: {  //规格弹出框
        title: '',
        gmtCreate: '',
        gmtUpdate: '',
        inputSkuTagVisible: false,  //输入框显示
        inputSkuTagValue: '',  //输入框绑定
        values: []  //标签数组
      },
      picList: [],  //图片数组
      imgPath: imgUrl,   //图片地址
      myHeaders: { AdminToken: token },  //图片上传请求头
      category: [],  //类目
      part: { //子集配置
        label: 'title',
        children: 'childrenList',
        value: 'id',
        emitPath: false
      },
      dialogFormVisible: false,  //商品参数显示
      specificationVisible: false,   //规格显示 
      priceVisible: false, //批量弹出框显示
      bool: false,  //规格添加或修改
      ind: 0, //规格表格下标
      skuPrice: {  //批量弹出框
        price: 1,
        vipPrice: 1,
        originalPrice: 1
      },
      loading: false //加载
    }
  },
  methods: {
    categoryTree() { //类目
      post({ _gp: 'admin.category', _mt: 'categoryTree' }).then(res => {
        this.category = res.data
      })
    },
    // 参数添加
    paramAdd(num) {
      if (num) {  //商品参数添加
        this.dialogFormVisible = true
        this.formPran = {}
      } else {  //规格添加
        this.specificationVisible = true
        this.bool = true
        Object.assign(this.specification, this.$options.data().specification)
      }
    },
    // 修改规格
    alter(row, index) {
      this.specificationVisible = true
      this.bool = false
      Object.assign(this.specification, row)
      this.ind = index
    },
    // 参数确定
    confirm() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          this.form.attributeList.push({ ...this.formPran })
          this.dialogFormVisible = false
        }
      })
    },
    // 创建 或修改规格
    addspecification() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          let specificationList = this.form.specificationList  //规格列表
          let spec = this.specification
          let num = specificationList.findIndex(item => item.title == spec.title)
          this.specificationVisible = false
          if (num == -1) {
            if (this.bool) return specificationList.push({ ...spec, gmtCreate: Date.now() })
            specificationList[this.ind].title = spec.title
            return
          }
          ElMessage.warning('已有重复的！')
        }
      })
    },
    // 删除规格 或删除商品
    remove(index, num) {
      ElMessageBox.confirm(
        '确定要删除吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          if (num) return this.form.attributeList.splice(index, 1)
          this.form.specificationList.splice(index, 1)
        })
    },
    // 添加标签
    addTab(ind) {
      this.form.specificationList[ind].inputSkuTagVisible = true  //当行的输入框显示
      this.specification.inputSkuTagValue = ''  //清空输入框
    },
    // 输入框失去焦点
    handleInputConfirm(index) {      //追加数据到列表末尾
      let input = this.specification.inputSkuTagValue  //输入框value
      let tagArr = this.form.specificationList[index].values //标签数组
      if (input) { //不为空
        let num = tagArr.findIndex(item => item == input)
        if (num == -1) {  // 去重
          tagArr.push(input)
        }
      }
      this.form.specificationList[index].inputSkuTagVisible = false
    },
    // 批量定价
    batch() {
      this.priceVisible = true
      Object.assign(this.skuPrice, this.$options.data().skuPrice)
    },
    // 批量确定
    batchConfirm() {
      this.priceVisible = false
      for (const s of this.form.skuList) {
        Object.assign(s, this.skuPrice)
      }
    },
    // sku图片上传
    handleImgSuccess(res, index) {
      this.loading = true
      if (200 == res.errno) {
        this.form.skuList[index].img = res.url
        this.loading = false
      }
    },
    // 跨行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 表格长度/第一行标签长度
      let rowSpan = this.form.skuList.length / this.form.specificationList[0].values.length
      for (let index = 0; index < this.form.specificationList.length; index++) {
        if (index !== 0) {
          rowSpan = rowSpan / this.form.specificationList[index].values.length
        }
        if (this.form.specificationList[index].values == 0) {
          return {
            rowspan: 1,
            colspan: 1
          }
        }
        if (columnIndex === index) {
          if (rowIndex % rowSpan === 0) {
            return {
              rowspan: rowSpan,
              colspan: 1
            };
          } else {
            return {
              rowspan: 0,
              colspan: 0
            };
          }
        }
      }
    },
    // 关闭商品
    closeShop() {
      this.$store.dispatch('close')
      this.$refs.shopRef.resetFields()
    },
    // 保存商品
    addShop() {
      this.$refs.shopRef.validate(valid => {
        if (valid) {
          post({ _gp: 'admin.product', _mt: 'create', spuDTO: JSON.stringify(this.form) }).then(res => {
            if (200 == res.errno) {
              ElMessageBox.confirm('是否继续添加?', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
              }).then(() => {
                this.$refs.shopRef.resetFields()  //重置表单
                Object.assign(this.form, this.$options.data().form)  //初始化数据
                this.picList = []
              }).catch(() => {
                this.$router.push('commList')
              })
            } else {
              ElMessage.error(res.errmsg)
            }
          })
        }
      })
    },
    // 商品图片上传成功
    handleAvatarSuccess(res, file) {
      if (200 == res.errno) {
        this.form.imgList.push(res.url)  //追加图片路径
        this.form.img = res.url
      }
      if (this.form.imgList.length == 5) {
        ElMessage.warning('图片最多上传五张！')
      }
    },
    // 删除图片
    handleRemove(res) {
      let ind = this.form.imgList.findIndex(item => item == res.response.url)  //删除图片路径
      this.form.imgList.splice(ind, 1)
    },
    // 商品图片上传更新
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片得是jpg类型!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片不能超过2MB!')
        return false
      }
      return true
    }
  },
  computed: {
    // Sku数据
    createSku() {
      let list = this.form.specificationList
      let valueList = list.map(item => item.values).filter(item => item.length > 0);
      let titles = list.filter(item => item.values.length > 0).map((item) => {
        return item.title
      });
      let sku = valueList.reduce((total, item) => { //笛卡尔计算 
        let arr = [];
        total.forEach((i) => {
          item.forEach((val) => {
            arr.push(i.concat([val]));   //交叉追加
          });
        });
        return arr;
      },
        [[]]
      );
      let arry = sku.map((item, ind) => { //构建数据
        let line = this.form.skuList.find(i => i.title == item.join(','))
        let obj = {
          title: [],
          originalPrice: 1,
          price: 1,
          vipPrice: 1,
          stock: 1,
          specification: [], //规格维度
          weight: 1,
          barCode: '',
          img: '',
        };
        item.forEach((val, index) => {
          let key = "id_" + titles[index];
          obj[key] = val;
          obj.title.push(val);
          obj.specification.push(titles[index] + "_" + val);
        })
        obj.title = obj.title.join(); //将标题数组转换为字符串
        obj.specification = obj.specification.join();
        Object.assign(obj, line)   //重新赋值
        return obj;
      })
      if (arry[0].title.length == 0) {  //删除完数据清空
        return []
      }
      this.form.skuList = arry
      return arry;
    }
  },
  created() {
    this.categoryTree()
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 120px;
  border: 1px #ccc dashed;
}
/deep/.avatar {
  width: 150px;
}
/deep/.icon {
  width: 150px;
  height: 50px;
}
.box {
  width: 50px;
  text-align: center;
}
.box .icon {
  width: 50px;
}
</style>
